package com.frank.jpaSpecification.controller;

import com.frank.jpaSpecification.entity.Mobile;
import com.frank.jpaSpecification.entity.PageParamRequest;
import com.frank.jpaSpecification.repository.MobileRepository;
import com.frank.jpaSpecification.service.MobileService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Optional;

/**
 * @author 小石潭记
 * @date 2020/12/12 14:24
 * @Description: ${todo}
 */
@RestController
@RequestMapping("/mobile")
public class MobileController {

    @Autowired
    private MobileService mobileService;

    @Autowired
    private MobileRepository repository;

    /**
     * 注意这里是从0页开始查询的
     * @param request
     * @return
     */
    @GetMapping("/list")
    public Page<Mobile> getAllMobileList(PageParamRequest request) {
        return mobileService.getAllMobile(request);
    }

    @GetMapping("/count")
    public Object getCount(String branch) {
        return repository.countByBranch(branch);
    }

    @GetMapping("/test")
    public Object test(String branch) {
        Mobile mobile = new Mobile();
        Optional<Mobile> frank = repository.findByBranch(branch);
        if (frank.isPresent()) {
            BeanUtils.copyProperties(frank.get(), mobile, "modifyDatetime");
        }
        mobile.setBranch(branch);
        mobile.setName(branch);
        mobile.setAddress("chongqing");
        return repository.save(mobile);
    }

    @GetMapping("/test1")
    public Object test1(String branch) throws InterruptedException {
        Mobile mobile = new Mobile();
        mobile.setBranch(branch);
        mobile.setName(branch);
        mobile.setAddress("chongqing");
        Optional<Mobile> frank = repository.findByBranch(branch);
        if (frank.isPresent()) {
            mobile.setId(frank.get().getId());
//            mobile.setCreateDatetime(frank.get().getCreateDatetime());
        }
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now);
        mobile.setModifyDatetime(now);
        /*Thread.sleep(1000);
        System.out.println(mobile);
        System.out.println(mobile.getModifyDatetime());*/
        Mobile save = repository.save(mobile);
        return save;
    }
}
